package com.fatan.xiaopacai.mvvm.viewmodel

import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import com.fatan.xiaopacai.base.BaseViewModel
import com.fatan.xiaopacai.mvvm.model.Player
import com.fatan.xiaopacai.mvvm.model.PuKe
import com.fatan.xiaopacai.mvvm.model.allPuKe
import com.fatan.xiaopacai.mvvm.model.nullPuke

/**
 * @author: WangYeTong
 * @date: 2024/1/8 17:44
 * @remake:
 */
class XiaoJiePukeViewModel : BaseViewModel() {
    /**
     * 玩家列表
     */
    private val _playerList = mutableStateOf<List<Player>>(listOf())
    val playerList: MutableState<List<Player>>
        get() = _playerList

    /**
     * 当前选中玩家的角标
     */
    private val _selectedPlayerIndex = mutableIntStateOf(0)
    val selectedPlayerIndex: MutableIntState
        get() = _selectedPlayerIndex

    /**
     * 长按选中的玩家角标
     */
    val longPressPlayerIndex = mutableIntStateOf(0)

    /**
     * 已经抽过的牌
     */
    private val _playedPuke = mutableStateOf<List<PuKe>>(listOf())
    val playedPuke: MutableState<List<PuKe>>
        get() = _playedPuke

    /**
     * 添加玩家
     */
    fun addPlayer(name: String) {
        _playerList.value = _playerList.value.toMutableList().apply { add(Player(name)) }
    }

    /**
     * 最新抽的牌
     */
    private val _newPuke = mutableStateOf(nullPuke)
    val newPuke: MutableState<PuKe>
        get() = _newPuke

    /**
     * 牌已发完的dialog
     */
    private val _showPukeFinishedDialog = mutableStateOf(false)
    val showPukeFinishedDialog: MutableState<Boolean>
        get() = _showPukeFinishedDialog

    /**
     * 删除玩家
     */
    fun removePlayer(player: Player) {
        _playerList.value = _playerList.value.toMutableList().apply { remove(player) }
    }

    /**
     * 重玩，洗牌
     */
    fun reset() {
        for (item in _playerList.value) {
            item.pukeList = listOf()
        }
        _playedPuke.value = listOf()
        _newPuke.value = nullPuke
    }

    fun setSelectedPlayerIndex(index: Int) {
        _selectedPlayerIndex.intValue = index
    }

    /**
     * 随机抽排
     */
    fun randomNewPuke() {
        if (_playedPuke.value.size >= allPuKe.size) {
            //牌已抽完，提示重新来过
            _showPukeFinishedDialog.value = true
            return
        }
        _newPuke.value = getRandomNotExit()
        //加入到数据中
        val newPlayer = _playerList.value[_selectedPlayerIndex.intValue]
        newPlayer.pukeList = newPlayer.pukeList.toMutableList().apply { add(_newPuke.value) }
    }

    private fun getRandomNotExit(): PuKe {
        val puke = allPuKe.random()
        if (_playedPuke.value.contains(puke)) {
            return getRandomNotExit()
        }
        _playedPuke.value = _playedPuke.value.toMutableList().apply { add(puke) }
        return puke
    }
}